#include "package.h"

PackageData::PackageData()
{
}

bool PackageData::load(const QString &filename, bool installed)
{
    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly))
        return false;

    QTextStream ts(&file);

    //packages.clear();
    PackageInfo pinfo;
    int count = 0;

    while (!ts.atEnd())
    {
        QString str = ts.readLine().simplified();
        if (str.isEmpty())
          continue;

        QStringList sl = str.split(" ", QString::SkipEmptyParts);
        QString param = sl.at(0), val = sl.at(1);

        if (param == "@package")
        {
            // append older one
          if (count++)
            packages[pinfo.name] = pinfo;

          if (packages.contains(val))
            pinfo = packages[val];
          else
            pinfo = PackageInfo();

            pinfo.name = val;
            continue;
        }

        if (param == "@version")
        {
          if (installed)
            pinfo.versionInstalled = val.toInt();
          else
            pinfo.versionServer = val.toInt();
          continue;
        }

        if (param == "@textversion")
        {
          if (installed)
            pinfo.versionInstalledText = val;
          else
            pinfo.versionServerText = val;
          continue;
        }

        if (param == "@required")
        {
            pinfo.required = val.toInt();
            continue;
        }

        if (param == "@extract")
        {
            pinfo.extractPath = val;
            continue;
        }

        if (param == "@target")
        {
            pinfo.target = val;
            continue;
        }

    }

    // append last package
    if (count++)
      packages[pinfo.name] = pinfo;

    // check state and actions
    QMap<QString, PackageInfo>::iterator it, it_end = packages.end();
    for (it = packages.begin(); it != it_end; it++)
    {
      PackageInfo &pack = *it;

      if (!pack.versionServer)
      {
        continue;
      }

      if (pack.versionInstalled == pack.versionServer)
      {
        pack.state = Installed;
        continue;
      }

      if (pack.versionInstalled < pack.versionServer)
      {
        pack.state = NotLoaded; // to do
        pack.action = LoadInstall;  // to do
        continue;
      }
    }

    return true;
}
